<?php
/**
 * http请求结束前的回调中间件
 * 供 路由到类 路由地址的格式为（动态方法）的路由地址使用
 *
 */

namespace app\http\Middleware;

use think\facade\Db;
use think\facade\Request;
use app\common\lib\MsgQueue;

class VisitMiddleware
{
    public function handle($request, \Closure $next)
    {
        return $next($request);
    }

    public function end(\think\Response $response)
    {
        $request = request();
        $path = $request->pathinfo();
        $method = $request->method();
        $requestData = $request->param();
        $requestData = $requestData ? $requestData : '';
        $responseData = $response->getContent();
        $httpCode = $response->getCode();

        $type = strtolower($request->type()); //xml json 等
//        $request->rule()->getMethod();//请求方式 get post 等
        $routeOptions = $request->rule()->getOption();//中间件 前缀 等信息对象
        $requestHeaders = $request->header();
        $requestHeaders = $requestHeaders ? $requestHeaders : [];
        $requestHeaders = filterHeaderData($requestHeaders);
        $requestHeaders = $requestHeaders ? $requestHeaders : '';

        $routeName = $request->rule()->getName();
        $routeMiddleware = $routeOptions['middleware'] ?? '';
        $routePrefix = $routeOptions['prefix'] ?? '';

        $data = [
            'http_code' => (string)$httpCode,
            'method' => strtoupper($method),
            'request_path' => is_string($path) ? $path : json_encode($path, JSON_UNESCAPED_UNICODE),
            'request_type' => $type,
            'route_name' => $routeName ?? '',
            'route_prefix' => $routePrefix,
            'middleware' => is_string($routeMiddleware) ? $routeMiddleware : json_encode($routeMiddleware, JSON_UNESCAPED_UNICODE),
            'header_data' => is_string($requestHeaders) ? $requestHeaders : json_encode($requestHeaders, JSON_UNESCAPED_UNICODE),
            'request_data' => is_string($requestData) ? $requestData : json_encode($requestData, JSON_UNESCAPED_UNICODE),
            'response_data' => is_string($responseData) ? $responseData : json_encode($responseData, JSON_UNESCAPED_UNICODE),
            'response_time' => date('Y-m-d H:i:s')
        ];
        $instance = [
            'response' => $response instanceof \think\Response,
            'view' => $response instanceof \think\response\View,
            'json' => $response instanceof \think\response\Json,
            'jsonp' => $response instanceof \think\response\Jsonp,
            'xml' => $response instanceof \think\response\Xml,
            'redirect' => $response instanceof \think\response\Redirect,
            'download' => $response instanceof \think\response\File,
        ];
        if ($instance['json'] || $instance['jsonp'] || $instance['xml']) {
            $mq = new MsgQueue();
            $mq->sendMessage(MsgQueue::QUEUE_RESPONSE_LOG, $data);
        }
    }
}